import cgi
import datetime
import logging
import urlparse

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import memcache
from google.appengine.api import urlfetch

logging.getLogger().setLevel(logging.DEBUG)


class MainPage(webapp.RequestHandler):
    def post(self):
        headers={'Content-Type':'application/xml'}
        payload = self.request.body
        logging.info(">>>>>[incoming] = {0}[EOF]".format(payload))
        #content = '<textarea cols="100" rows="10">' + payload + "</textarea>"
        #data = urlfetch.fetch('http://server4.operamini.com', payload=self.request.body, method=urlfetch.POST, headers=headers)
        data = {
            'status_code': 200,
            'content': 'content'
        }
        # set data to cache
        memcache.add("input", payload, 10)
        logging.info(">>>>>memcache updated!")
        self.response.status = data['status_code'] #data.status_code
        self.response.headers.add_header('Content-Type', 'text/html') # 'application/octet-stream'
        self.response.headers.add_header('Cache-Control', 'private, no-cache')
        self.response.out.write('ok') #data.content

    def get(self):
        self.response.status = '200 OK'
        self.response.headers.add_header('Content-Type', 'text/html')
        self.response.out.write('This is Opera Mini Server Proxy!')


class CachePage(webapp.RequestHandler):
    def get(self):
        inputData = memcache.get("input")
        logging.info(">>>>>[memcache] = {0}[EOF]".format(inputData))

        self.response.status = '200 OK'
        self.response.headers.add_header('Content-Type', 'text/html')
        self.response.headers.add_header('Cache-Control', 'private, no-cache')

        if inputData is not None:
            data = len(inputData)
        else:
            data = "no data"

        self.response.out.write("input data: >> {0}".format(data))

application = webapp.WSGIApplication([
    ('/', MainPage),
    ('/cache', CachePage)
], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
